<!-- eslint-disable no-empty -->
<template>
  <div class="user-profile">
    <el-card class="profile-card" shadow="always">
      <div class="header-section">
        <h2 class="title">个人信息管理</h2>
        <el-divider class="divider" />
        <p class="subtitle">管理您的旅游偏好和账户设置</p>
      </div>
      
      <el-form 
        :model="userForm" 
        ref="formRef" 
        label-width="120px" 
        :rules="rules"
      >
        <!-- 头像上传 -->
        <el-form-item label="个人头像">
          <div class="avatar-container">
            <el-avatar
              :src="userForm.avatar"
              :size="100"
              @error="handleAvatarError"
            />
            <div class="upload-container">
              <label class="upload-btn">
                <input
                  type="file"
                  accept="image/*"
                  @change="handleFileChange"
                />
                <el-icon><UploadFilled /></el-icon>
              </label>
              <p>点击上传或拖放图片</p>
              <p class="upload-tips">支持 JPG、PNG 格式，大小不超过 2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- 基本信息 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        
        <el-form-item label="生日" prop="birthdate">
          <el-date-picker 
            v-model="userForm.birthdate" 
            type="date"
            placeholder="选择生日"
            style="width: 100%"
          />
        </el-form-item>
        
        <!-- 旅游偏好 -->
        <el-form-item label="旅游偏好">
          <el-checkbox-group v-model="userForm.preferences">
            <el-checkbox 
              v-for="option in preferenceOptions"
              :key="option.value"
              :label="option.value"
              style="margin-right: 15px"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="资金预算">
          <el-input-number 
            v-model="userForm.budget"
            :min="0"
            :step="100"
            style="width: 100%"
          >
            <template #append>元</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="最远旅行距离">
          <el-select 
            v-model="userForm.maxTravelDistance" 
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option 
              v-for="item in distanceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="旅行频率">
          <el-select 
            v-model="userForm.travelFrequency" 
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option 
              v-for="item in frequencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <div class="button-container">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitLoading"
            style="width: 48%"
          >
            <el-icon><Save /></el-icon>
            保存
          </el-button>
          <el-button 
            @click="showLogoutDialog = true" 
            type="danger"
            style="width: 48%"
          >
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </el-form>
    </el-card>
    
    <!-- 退出确认对话框 -->
    <el-dialog 
      v-model="showLogoutDialog" 
      title="退出登录"
      width="400px"
      :show-close="false"
    >
      <div class="dialog-content">
        <el-icon class="dialog-icon"><WarningFilled /></el-icon>
        <p class="dialog-text">确定要退出当前账户吗？</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLogoutDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmLogout">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getUserInfoService,
  updateUserInfoService,
} from '@/api/user'
import { 
  Save,
  SwitchButton,
  WarningFilled,
  UploadFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref(null)
const submitLoading = ref(false)
const showLogoutDialog = ref(false)

// 默认头像 URL
const defaultAvatar = 'https://th.bing.com/th/id/OIP.g5M-iZUiocFCi9YAzojtRAAAAA?o=7&cb=iwp2rm=3&rs=1&pid=ImgDetMain'

// 用户表单数据
const userForm = ref({
  // 默认数据
  username: '旅行者',
  phone: '13800138000',
  email: 'traveler@example.com',
  birthdate: new Date('1990-01-01'),
  preferences: ['nature', 'food'],
  budget: 5000,
  maxTravelDistance: '1000km',
  travelFrequency: 'yearly',
  acceptRecommendations: true,
  avatar: defaultAvatar,
  avatarFile: null
})

// 验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ]
})

const preferenceOptions = [
  { label: '自然风光', value: 'nature' },
  { label: '历史人文', value: 'history' },
  { label: '美食体验', value: 'food' },
  { label: '冒险运动', value: 'adventure' },
  { label: '城市探索', value: 'city' },
  { label: '摄影', value: 'photography' },
  { label: '购物', value: 'shopping' },
  { label: '度假放松', value: 'relax' },
  { label: '文化体验', value: 'culture' },
  { label: '徒步旅行', value: 'hiking' }
]

const distanceOptions = [
  { value: '500km', label: '500公里以内' },
  { value: '1000km', label: '1000公里以内' },
  { value: '2000km', label: '2000公里以内' },
  { value: 'national', label: '全国范围内' },
  { value: 'international', label: '国际旅行' }
]

const frequencyOptions = [
  { value: 'daily', label: '几乎每天' },
  { value: 'weekly', label: '每周' },
  { value: 'monthly', label: '每月' },
  { value: 'quarterly', label: '每季度' },
  { value: 'yearly', label: '每年' },
  { value: 'rarely', label: '偶尔' }
]

// 获取用户信息
onMounted(async () => {
  try {
    const res = await getUserInfoService()
    // 只有当后端返回的数据存在时，才更新表单
    if (res.data && Object.keys(res.data).length > 0) {
      userForm.value = {
        ...userForm.value,
        ...res.data,
        avatar: res.data.avatar || defaultAvatar
      }
    }
  // eslint-disable-next-line no-empty
  } catch (error) {

  }
})

// 处理头像加载错误
const handleAvatarError = (e) => {
  e.target.src = defaultAvatar
}

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (!file) return
  
  // 检查文件大小和类型
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 2MB')
    return
  }
  
  if (!file.type.match('image.*')) {
    ElMessage.error('请上传图片文件')
    return
  }
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (event) => {
    userForm.value.avatar = event.target.result
    userForm.value.avatarFile = file
  }
  reader.readAsDataURL(file)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  submitLoading.value = true
  try {
    await formRef.value.validate()
    
    // 构建要发送的数据（如果头像是默认的，则不发送文件）
    const formData = new FormData()
    formData.append('username', userForm.value.username)
    formData.append('phone', userForm.value.phone)
    formData.append('email', userForm.value.email)
    formData.append('birthdate', userForm.value.birthdate.toISOString())
    formData.append('preferences', JSON.stringify(userForm.value.preferences))
    formData.append('budget', userForm.value.budget)
    formData.append('maxTravelDistance', userForm.value.maxTravelDistance)
    formData.append('travelFrequency', userForm.value.travelFrequency)
    formData.append('acceptRecommendations', userForm.value.acceptRecommendations)
    
    // 只有当用户更改了头像时才上传
    if (userForm.value.avatarFile) {
      formData.append('avatar', userForm.value.avatarFile)
    }
    
    // 这里需要根据实际的 API 接口调整
    // 简化为直接调用更新 API
    await updateUserInfoService(formData)
    
    // 保存用户信息到本地存储
    const userInfo = {
      ...userForm.value,
      avatar: userForm.value.avatar
    }
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('更新失败，请检查输入信息')
  } finally {
    submitLoading.value = false
  }
}

// 确认退出登录
const confirmLogout = async () => {
  try {
    showLogoutDialog.value = false
    ElMessage.success('已退出登录')
    router.push('/login')
  // eslint-disable-next-line no-empty
  } catch (error) {
  }
}
</script>

<style scoped>
.user-profile {
  padding: 20px;
  max-width: 700px;
  margin: 0 auto;
}

.profile-card {
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.profile-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.header-section {
  margin-bottom: 25px;
  text-align: center;
}

.title {
  margin-bottom: 15px;
  color: #303133;
  font-size: 24px;
}

.divider {
  margin: 10px auto 15px;
}

.subtitle {
  color: #606266;
  font-size: 14px;
}

.button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.el-form-item {
  margin-bottom: 24px;
}

/* 头像上传样式 */
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-avatar {
  margin-bottom: 15px;
  cursor: pointer;
}

.upload-container {
  text-align: center;
}

.upload-btn {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 1px 30px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-btn:hover {
  border-color: #409EFF;
}

.upload-btn input {
  display: none;
}

.upload-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.dialog-icon {
  color: #f56c6c;
  font-size: 36px;
  margin-right: 15px;
}

.dialog-text {
  font-size: 16px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .profile-card {
    padding: 20px 15px;
  }
  
  .button-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .button-container .el-button {
    width: 100% !important;
  }
}
</style>